package com.yupi.generator;

import com.yupi.model.MainTemplateConfig;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class DynamicGenerator {
    public static void main(String[] args) throws IOException, TemplateException {
        //ftl路径
        String projectPath = System.getProperty("user.dir");
        String inputPath = projectPath + File.separator + "src/main/resources/templates/MainTemplate.java.ftl";
        //outputPath
        String outputPath = projectPath+File.separator+"MainTemplate.java";
        //创建model
        MainTemplateConfig mainTemplateConfig = new MainTemplateConfig();
        mainTemplateConfig.setAuthor("dingmingjie");
        mainTemplateConfig.setLoop(true);
        mainTemplateConfig.setOutputText("数的总和:");

        //生成
        doGenerate(inputPath,outputPath,mainTemplateConfig);
    }

    public static void doGenerate(String inputPath, String outputPath, Object model) throws TemplateException, IOException {
        /**
         * @Author: ding
         * @Description: 生成文件
         * @Params: [inputPath ftl文件, outputPath, model 数据模型]
         * @Return: void
         */
        // new 出 Configuration 对象，参数为 FreeMarker 版本号
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_32);

        // 指定模板文件所在的路径
        File ftlPath = new File(inputPath);
        File templateDir = ftlPath.getParentFile();
        configuration.setDirectoryForTemplateLoading(templateDir);

        // 设置模板文件使用的字符集
        configuration.setDefaultEncoding("utf-8");
        //调整输出数字格式 2023 取代 2,023
        configuration.setNumberFormat("0.######");
        //模板文件
        Template template = configuration.getTemplate(ftlPath.getName());
        //生成导出
        Writer writer = new FileWriter(outputPath);
        template.process(model, writer);
        writer.close();
    }
}
